package ua.com.abakumov.android.prostopleer.activities

import scala.collection.JavaConversions._
import android.app.Activity
import android.os.Bundle
import android.widget._
import android.view.{Gravity, MenuItem, Menu, View}
import android.content.Intent

import ua.com.abakumov.android.R

import java.util.{List => JList}
import ua.com.abakumov.android.prostopleer.engines.ProstoPlayerEngine
import ua.com.abakumov.android.prostopleer.util.UI._
import ua.com.abakumov.android.prostopleer.util.Functions._

import ua.com.abakumov.android.prostopleer.tasks.GTask
import ua.com.abakumov.android.prostopleer.util.Composition


/**
 * MainActivity
 *
 * @author alexander-abakumov
 *         Date: 04.09.12
 */
class MainActivity extends Activity {
  private val engine = new ProstoPlayerEngine

  override def onCreateOptionsMenu(menu: Menu): Boolean = {
    getMenuInflater.inflate(R.menu.main, menu)
    true
  }

  /**
   * Menu selected
   *
   * @param item menu item
   * @return
   */
  override def onOptionsItemSelected(item: MenuItem): Boolean = {
    item.getItemId match {
      case R.id.about_menu => startActivity(new Intent("ACTION_ABOUT"))
      case R.id.settings_menu => startActivity(new Intent("ACTION_SETTINGS"))
      case _ => super.onOptionsItemSelected(item)
    }

    true
  }

  protected override def onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)

    // Search
    val searchButton = findViewById(R.id.searchButton).asInstanceOf[Button]

    searchButton.setOnClickListener((view: View) => {

      val textEdit: EditText = findViewById(R.id.entry).asInstanceOf[EditText]

      hideKeyboard(textEdit, this)

      val search = textEdit.getText.toString.trim

      if (!search.isEmpty) {
        val gt = new GTask((result: JList[Composition]) => {
          setFoundCount(result.size, search)

          if (result.size > 0) {
            clearFoundResults()
            setFoundResults(result)
          }
        })
        gt.execute(search, engine)
      } else {
        toast(getString(R.string.incorrect_search_text), MainActivity.this)
      }
    })

    searchButton.setOnLongClickListener((view: View) => {
      findViewById(R.id.entry).asInstanceOf[EditText].setText("")
      true
    })

    engine.setListeners((x:String) =>
      // Saved
      toast(getString(R.string.file_has_been_saved, x), MainActivity.this)
    , (x:String) =>
      // Started
      toast(getString(R.string.downloading_started), MainActivity.this)
    , _ =>
      // Card isn't available
      alert(getString(R.string.error), getString(R.string.mount_ext_card), MainActivity.this)
    )
  }

  /**
   * Update UI label
   * @param count count
   * @param searchRequest search string
   */
  private def setFoundCount(count: Int, searchRequest: String) {
    findViewById(R.id.searchFoundCount).asInstanceOf[TextView].setText("%s, %s".format(count, searchRequest))
  }

  private def clearFoundResults() {
    findViewById(R.id.mainTable).asInstanceOf[TableLayout].removeAllViews()
  }

  private def setFoundResults(compositions: java.util.List[Composition]) {
    val tableLayout = findViewById(R.id.mainTable).asInstanceOf[TableLayout]

    compositions.foreach(c => {
      val row = new TableRow(MainActivity.this)

      row.setGravity(Gravity.CENTER_VERTICAL)
      row.addView(createTextView(c.artist, MainActivity.this))
      row.addView(createTextView(c.song, MainActivity.this))
      row.addView(createTextView(c.size, MainActivity.this))

      val downloadButton: ImageButton = new ImageButton(MainActivity.this)
      downloadButton.setImageResource(R.drawable.av_download)
      downloadButton.setOnClickListener((view: View) => {
        downloadComposition(c)
      })

      row.addView(downloadButton)

      /* Add row to TableLayout. */
      tableLayout.addView(row)
    })
  }

  /**
   * Download and save composition
   *
   * @param composition composition
   */
  private def downloadComposition(composition: Composition) {
    engine.download(composition)
  }
}